package com.congwulin.wechat.util;

import com.congwulin.wechat.entity.common.SuperVO;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class VOTsCheck {


    /**
     * 校验实体VO的时间戳与数据库中的时间戳是否一致
     *
     * @param vo 实体VO
     * @param tablename 实体VO对应的数据库表表名
     */
    public void check(SuperVO vo, String tablename) {
        SuperVO[] vos = new SuperVO[] { vo };
        this.check(vos, tablename);
    }

    /**
     * 校验实体VO数组的时间戳与数据库中的时间戳是否一致
     *
     * @param vo 实体VO数组
     * @param tablename 实体VO对应的数据库表表名
     */
    public void check(SuperVO[] vos, String tablename) {
        Map<String, Timestamp> index = this.group(vos);
        int size = index.size();
        String[] ids = new String[size];
        ids = index.keySet().toArray(ids);
        TsDbLoader loader = SpringUtil.getBean(TsDbLoader.class);
        Map<String, Timestamp> dbIndex = loader.query(ids, tablename);
        this.compareTs(index, ids, dbIndex);
    }

    private void compareTs(Map<String, Timestamp> index, String[] ids, Map<String, Timestamp> dbIndex) {
        if (dbIndex.size() != index.size()) {
            String message = "实体数据与数据库数据不一致，请刷新";
            ExceptionUtils.wrapBusinessException(message);
        }
        for (String id : ids) {
            Timestamp voTs = index.get(id);
            Timestamp dbTs = dbIndex.get(id);
            if (!this.isEqual(voTs, dbTs)) {
                String message = "实体数据与数据库数据不一致，请刷新";
                ExceptionUtils.wrapBusinessException(message);
            }
        }
    }

    private Map<String, Timestamp> group(SuperVO[] vos) {
        Map<String, Timestamp> index = new HashMap<String, Timestamp>();
        for (SuperVO vo : vos) {
            String id = vo.getId();
            Timestamp ts = vo.getTs();
            if (id == null || ts == null) {
                IllegalArgumentException ex = new IllegalArgumentException("时间戳和主键不能为空");
                throw ex;
            }
            index.put(id, ts);
        }
        return index;
    }

    private boolean isEqual(Timestamp one, Timestamp two) {
        //过滤掉毫秒
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String oneTs = format.format(one);
        String twoTs = format.format(two);

        return oneTs.equals(twoTs);
    }
}
